//
//  EpointPersonChooseViewController.m
//  EpointFrame5
//
//  Created by 李亚春 on 13-12-18.
//  Copyright (c) 2013年 Epoint. All rights reserved.
//

#import "EpointPersonChooseViewController.h"
#import "EpointPersonChooseProtocol.h"
#import "EpointSettingViewController.h"
#import "UIViewController+MJPopupViewController.h"
#import "EpointPersonModelViewViewController.h"
#import "EpointPersonChooseListCell.h"

#define QueryTaskID 1
#define QueryAddressBookGroupTaskId 2
#define QueryAddressBookListTaskId 3

@interface EpointPersonChooseViewController ()
{
    NSMutableArray *dataArray,*flagArr;
    NSMutableArray *choosedPersons;
    UITableView *tv;
    UISearchBar *sb;
    UISearchDisplayController *searchController;
//    UISegmentedControl *sc;
    UIButton *btBack,*btFullChoose,*btClear,*btOK;
    FPPopoverController *popoverCtrl;
    PopElementView *elementView;
    NSArray *selectionArray;
    int selectionIndex;
}
@end

@implementation EpointPersonChooseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dataArray = [[NSMutableArray alloc]init];
        flagArr = [[NSMutableArray alloc]init];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    choosedPersons = [initParam objectForKey:EpointPersonChoosedPerson];
    [self changeAlreadyChooseTitle];
    
    self.title = @"人员选择";
    
    sb = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, AppWidth, 44)];
    sb.placeholder = @"输入姓名或拼音首字母查询";
    [self.view addSubview:sb];
    
    [self popoverCtrl];
    
    UIColor *btColor = COLOR(248, 246, 250);
    UIView *btPanel = [[UIView alloc]initWithFrame:CGRectMake(0, 44, AppWidth, 40)];
    btPanel.backgroundColor =btColor;
    btPanel.layer.borderWidth = 1;
    [btPanel.layer setBorderColor:[COLOR(181, 181, 181) CGColor]];
    
    btBack = [[UIButton alloc]initWithFrame:CGRectMake(AppWidth-80*4, 0, 80, 40)];
    [btBack setTitle:@"上级" forState:UIControlStateNormal];
    btBack.backgroundColor = btColor;
    [btBack setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btBack setTitleColor:COLOR(220, 221, 74) forState:UIControlStateHighlighted];
    [btBack addTarget:self action:@selector(upLevel) forControlEvents:UIControlEventTouchUpInside];
    [btPanel addSubview:btBack];
    
    btFullChoose = [[UIButton alloc]initWithFrame:CGRectMake(AppWidth-80*3, 0, 80, 40)];
    [btFullChoose setTitle:@"全选" forState:UIControlStateNormal];
    btFullChoose.backgroundColor = btColor;
    [btFullChoose setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btFullChoose setTitleColor:COLOR(220, 221, 74) forState:UIControlStateHighlighted];
    [btFullChoose addTarget:self action:@selector(fullChooseAction) forControlEvents:UIControlEventTouchUpInside];
    [btPanel addSubview:btFullChoose];
    
    btClear = [[UIButton alloc]initWithFrame:CGRectMake(AppWidth-80*2, 0, 80, 40)];
    [btClear setTitle:@"清空" forState:UIControlStateNormal];
    btClear.backgroundColor = btColor;
    [btClear setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btClear setTitleColor:COLOR(220, 221, 74) forState:UIControlStateHighlighted];
    [btClear addTarget:self action:@selector(clearChoosePerson) forControlEvents:UIControlEventTouchUpInside];
    [btPanel addSubview:btClear];
    
    btOK = [[UIButton alloc]initWithFrame:CGRectMake(AppWidth-80*1+18, 0, 40, 40)];
    [btOK setImage:[UIImage imageNamed:@"img_bz2"] forState:UIControlStateNormal];
    btOK.backgroundColor = btColor;
    [btOK addTarget:self action:@selector(chooseSelectionAction:) forControlEvents:UIControlEventTouchUpInside];
    [btPanel addSubview:btOK];
    [self.view addSubview:btPanel];
    
    tv = [[UITableView alloc]initWithFrame:CGRectMake(0, btPanel.frame.origin.y+btPanel.frame.size.height, AppWidth, AppHeight-64-88)];
    tv.dataSource = self;
    tv.delegate = self;
    [self.view addSubview:tv];
    
    sb.delegate = self;
    searchController = [[UISearchDisplayController alloc]initWithSearchBar:sb contentsController:self];
    searchController.searchResultsTableView.backgroundColor = [UIColor whiteColor];
    searchController.delegate = self;
    searchController.searchResultsDataSource = self;
    searchController.searchResultsDelegate = self;
    searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    searchController.searchResultsTableView.bounces = NO;
    
    if([[initParam objectForKey:@"hasDefault"]isEqualToString:@"1"])
    {
        btPanel.hidden = YES;
        sb.hidden=YES;
        dataArray = [initParam objectForKey:@"DefaultUsers"];
        [tv setFrame:CGRectMake(0, sb.top, AppWidth, AppHeight-64)];
        
        [tv reloadData];
    }
    else{
        [self getData:@""];
    }
}

-(void)fullChooseAction
{
    for (int i=0; i<dataArray.count; i++) {
        NSMutableDictionary *m = [dataArray objectAtIndex:i];
        NSString *guid = [m objectForKey:@"guid"];
        NSString *type = [m objectForKey:@"type"];
        
        if ([type isEqualToString:@"ou"])
        {

        }
        else if([type isEqualToString:@"user"])
        {
            
            BOOL isContant = NO;
            NSMutableDictionary *containDic;
            for (int i=0; i<choosedPersons.count; i++) {
                NSMutableDictionary *cd = [choosedPersons objectAtIndex:i];
                if ([[cd objectForKey:@"guid"]isEqualToString:guid]) {
                    containDic = cd;
                    isContant = YES;
                    break;
                }
            }
            
            if (isContant) {
//                [choosedPersons removeObject:containDic];
            }
            else
            {
                [choosedPersons addObject:m];
            }
            
            
            [tv reloadData];
            [searchController.searchResultsTableView reloadData];
            
            [self changeAlreadyChooseTitle];
        }
    }
}

-(void)clearChoosePerson
{
    [choosedPersons removeAllObjects];
    [tv reloadData];
    [self changeAlreadyChooseTitle];
}

-(void)chooseSelectionAction:(UIButton*)send
{
    if (!popoverCtrl.showed) {
        [popoverCtrl presentPopoverFromView:send];
    }
}

- (FPPopoverController *)popoverCtrl {
    if (popoverCtrl == nil) {
        selectionArray = @[@"所有部门", @"我的部门",@"我的地址簿",@"已选人员"];
        elementView = [[PopElementView alloc] initWithFrame:CGRectMake(0, 0, 160, PopElementItemHeight*selectionArray.count)];
        elementView.delegate = self;
        elementView.titles = selectionArray;
        [elementView selectItemAtIndex:0];
        
        popoverCtrl = [[FPPopoverController alloc] initWithView:elementView];
        popoverCtrl.arrowDirection = FPPopoverArrowDirectionUp;
        popoverCtrl.contentSize = CGSizeMake(170, PopElementItemHeight*selectionArray.count+10+FP_POPOVER_ARROW_HEIGHT);
        popoverCtrl.delegate = self;
    }
    return popoverCtrl;
}

#pragma mark - FPPopoverControllerDelegate

-(void)popoverControllerDidDismissPopover:(FPPopoverController *)popoverController{
    
}

-(void)presentedNewPopoverController:(FPPopoverController *)newPopoverController shouldDismissVisiblePopover:(FPPopoverController *)visiblePopoverController{
    
}

- (void)popElementViewDidSelectedAtIndex:(int)index {
    selectionIndex = index;
    if(index==0) {
        NSString *guid = @"";
        if (flagArr.count>0) {
            guid =[flagArr objectAtIndex:flagArr.count-1];
        }
        [self getData:guid];
        [tv reloadData];
        btBack.hidden = NO;
    }
    else if(index==2)
    {
        [self showMBPHUD];
        [self startTask:@"EpointGetAddressBookGroup" withParams:nil withTaskId:QueryAddressBookGroupTaskId];
    }
    else if(index==3)
    {
        dataArray = choosedPersons;
        [tv reloadData];
        
    }
    else if(index==1)
    {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        NSString *ug = [ud objectForKey:Epoint_User_UserGuid];
        NSString *ouguid = [[DBFrameService getUserDetailByUserguid:ug]objectForKey:@"ouguid"];
        [self getData:ouguid];
        [tv reloadData];
    }
    
    if (index>0) {
        btBack.hidden = YES;
    }
    [popoverCtrl dismissPopoverAnimated:YES];
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView
{
    [tv setHidden:NO];
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView
{
    [tv setHidden:YES];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:searchText forKey:@"keyword"];
    [self startTask:@"EpointQueryContactsTask" withParams:params withTaskId:QueryTaskID];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"searchBarSearchButtonClicked");
    [searchBar resignFirstResponder];
    [self doSearch:searchBar];
    
    [searchController setActive:NO animated:YES];
}

- (void)doSearch:(UISearchBar *)searchBar{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:searchBar.text forKey:@"keyword"];
    [self startTask:@"EpointQueryContactsTask" withParams:params withTaskId:QueryTaskID];
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    sb.showsCancelButton = NO;
}

-(void)upLevel
{
    if (flagArr.count==0) {
        
    }
    else if(flagArr.count==1)
    {
        [self getData:@""];
    }
    else
    {
        [self getData:[flagArr objectAtIndex:flagArr.count - 2]];
    }
    
    if (flagArr.count>0) {
        [flagArr removeObjectAtIndex:flagArr.count-1];
        if (flagArr.count==0) {
        }
    }
}

-(void)getData:(NSString *)_parentguid
{
    dataArray = [DBFrameService getContactsListByParentGuid:_parentguid];
    [searchController.searchResultsTableView reloadData];
    [tv reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 47;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"EpointPersonChooseListCell";
    EpointPersonChooseListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
            NSString *nibName = @"EpointPersonChooseListCell";
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:nibName owner:self options:nil];
            cell = [nib objectAtIndex:0];
    }
    
    cell.backgroundColor = [UIColor clearColor];
    NSMutableDictionary *m = [dataArray objectAtIndex:indexPath.row];
    NSString *type = [m objectForKey:@"type"];
    NSString *guid = [m objectForKey:@"guid"];
    cell.lbTitle.text = [m objectForKey:@"name"];
    [cell.imageView setContentMode:UIViewContentModeScaleAspectFit];
    cell.lbTitle.textColor = COLOR(90, 68, 103);
    if ([type isEqualToString:@"user"]) {
        [cell.ivHead setImage:[UIImage imageNamed:@"img_personchoose_user"]];
        cell.lbDetail.text = [m objectForKey:@"ouname"];
        cell.lbDetail.hidden = NO;
        BOOL isChoose = NO;
        
        for (int i=0; i<choosedPersons.count; i++) {
            NSMutableDictionary *cd = [choosedPersons objectAtIndex:i];
            if ([[cd objectForKey:@"guid"] isEqualToString:guid]) {
                isChoose = YES;
                break;
            }
        }
        
        if (isChoose) {
            cell.ivCheck.hidden = NO;
        }
        else
        {
            cell.ivCheck.hidden = YES;
        }
    }
    else
    {
        [cell.ivHead setImage:[UIImage imageNamed:@"img_personchoose_ou"]];
        cell.textLabel.textColor = [UIColor blackColor];
        cell.detailTextLabel.text = @"";
        cell.ivCheck.hidden = YES;
        cell.lbTitle.center = CGPointMake(165,47/2);
        cell.lbDetail.hidden = YES;
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *m = [dataArray objectAtIndex:indexPath.row];
    if (selectionIndex==2&&[[m objectForKey:@"type"]isEqualToString:@"ou"]) {
        [self showMBPHUD];
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:[m objectForKey:@"guid"] forKey:@"groupguid"];
        [self startTask:@"EpointGetAddressBook" withParams:params withTaskId:QueryAddressBookListTaskId];
        return;
    }
    [self addSinglePerson:[dataArray objectAtIndex:indexPath.row]];
}

-(void)addSinglePerson:(NSMutableDictionary *)m
{
    NSString *guid = [m objectForKey:@"guid"];
    NSString *type = [m objectForKey:@"type"];
    
    if ([type isEqualToString:@"ou"])
    {
        [self getData:guid];
        [flagArr addObject:guid];
    }
    else if([type isEqualToString:@"user"])
    {
        
        BOOL isContant = NO;
        NSMutableDictionary *containDic;
        for (int i=0; i<choosedPersons.count; i++) {
            NSMutableDictionary *cd = [choosedPersons objectAtIndex:i];
            if ([[cd objectForKey:@"guid"]isEqualToString:guid]) {
                containDic = cd;
                isContant = YES;
                break;
            }
        }
        
        if (isContant) {
            [choosedPersons removeObject:containDic];
        }
        else
        {
            [choosedPersons addObject:m];
        }
        
        
        [tv reloadData];
        [searchController.searchResultsTableView reloadData];
        
        [self changeAlreadyChooseTitle];
    }
}

-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj
{
    if (taskId==QueryTaskID) {
        dataArray = (NSMutableArray *)obj;
        [tv reloadData];
        [searchController.searchResultsTableView reloadData];
    }
    else if (taskId==QueryAddressBookGroupTaskId||taskId==QueryAddressBookListTaskId)
    {
        [self hideMBPHUD];
        //处理异常信息
        NSMutableArray *arr = (NSMutableArray*)obj;
        if (![[arr objectAtIndex:0]isEqualToString:@"1"]) {
            [dataArray removeAllObjects];
        }
        else
        {
            dataArray = [arr objectAtIndex:2];
        }
        [tv reloadData];
    }
}

-(void)changeAlreadyChooseTitle
{
    NSString *title = [NSString stringWithFormat:@"确定(%lu)",(unsigned long)choosedPersons.count];
    
    [self setRightBarButtonItemWithTitle:title action:@selector(okButtonAction)];
}

-(void)okButtonAction
{
    [self.navigationController popViewControllerAnimated:YES];
    EpointPhoneViewController *vc =  [initParam objectForKey:EpointPersonIntentContext];
    NSString *tag = [initParam objectForKey:EpointPersonIntentTag];
    [vc epointPerson:tag chooseData:choosedPersons];
}

+(NSArray *)getChoosedArray:(NSMutableArray *)data
{
    NSMutableString *names = [[NSMutableString alloc]initWithString:@""];
    NSMutableString *guids = [[NSMutableString alloc]initWithString:@""];
    for (int i=0; i<data.count; i++) {
        NSMutableDictionary *dic = [data objectAtIndex:i];
        NSString *name = [dic objectForKey:@"name"];
        NSString *guid = [dic objectForKey:@"guid"];
        [names appendString:name];
        [names appendString:@";"];
        [guids appendString:guid];
        [guids appendString:@";"];
    }
    NSArray *arr = [[NSArray alloc]initWithObjects:names,guids,nil];
    return arr;
}

+(NSMutableArray *)generateChoosedPerson:(NSString *)names guids:(NSString *)guids
{
    NSArray *nameArr = [names componentsSeparatedByString:@";"];
    NSArray *guidArr = [guids componentsSeparatedByString:@";"];
    NSMutableArray *cdArr  = [[NSMutableArray alloc]init];
    if (nameArr.count!=guidArr.count||nameArr.count==0||guidArr.count==0) {
        return cdArr;
    }
    else
    {
        for (int i=0; i<nameArr.count; i++) {
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
            NSString *name = [nameArr objectAtIndex:i];
            NSString *guid = [guidArr objectAtIndex:i];
            [dic setObject:name forKey:@"name"];
            [dic setObject:guid forKey:@"guid"];
            [dic setObject:@"user" forKey:@"type"];
            if (name.length!=0&&guid.length!=0) {
                [cdArr addObject:dic];
            }
        }
        return cdArr;
    }
}

+(void)pushChoosePerson:(EpointPhoneViewController *)context WithTag:(NSString *)tag AndNames:(NSString *)names AndGuids:(NSString *)guids
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:context forKey:EpointPersonIntentContext];
    [params setObject:tag forKey:EpointPersonIntentTag];
    [params setObject:[EpointPersonChooseViewController generateChoosedPerson:names guids:guids] forKey:EpointPersonChoosedPerson];
    EpointPhoneViewController *vc = [[EpointPersonChooseViewController alloc]initWithParams:params];
    [context.navigationController pushViewController:vc animated:YES];
}

+(void)pushChoosePerson:(EpointPhoneViewController *)context WithTag:(NSString *)tag AndNames:(NSString *)names AndGuids:(NSString *)guids withDefaultNames:(NSString *)defaultNames withDefaultGuids:(NSString *)defaultGuids
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:context forKey:EpointPersonIntentContext];
    [params setObject:tag forKey:EpointPersonIntentTag];
    [params setObject:[EpointPersonChooseViewController generateChoosedPerson:names guids:guids] forKey:EpointPersonChoosedPerson];
    [params setObject:@"1" forKey:@"hasDefault"];
    [params setObject:[EpointPersonChooseViewController generateChoosedPerson:defaultNames guids:defaultGuids] forKey:@"DefaultUsers"];
    EpointPhoneViewController *vc = [[EpointPersonChooseViewController alloc]initWithParams:params];
    [context.navigationController pushViewController:vc animated:YES];
}

@end
